package com.example.mtblog.tool;

import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
public class StrUtils {
    public static StringBuffer changeToIn(String data) {
        if(data == null || data.isEmpty())
            return null;
        String[] friends = data.split(",");
        StringBuffer res= new StringBuffer();
        for (String friend : friends) {
            res.append("'").append(friend).append("',");
        }
        return  res;
    }

    public static boolean judge(String item,String data){
        if(data==null || data.isEmpty() || item == null)
            return false;


        String [] strings=data.split(",");
        for(String str:strings){
            if(item.equals(str))
                return  true;
        }
        return false;
    }
    public static Integer findIndex(String item,String data){
        if(data==null || data.isEmpty())
            return -1;

        String [] strings=data.split(",");
        for(int i =0; i<strings.length ;i+=1){

            if(strings[i].equals(item))
                return  i;
        }
        return -1;
    }
    public static String insert(String item,String data){
        if(data==null || data.isEmpty() || item == null)
            return item;
        String newdata="";
        String [] strings=data.split(",");
            for(String str:strings){
                if(! item.equals(str) && !str.isEmpty())
                    newdata=newdata + str + ",";

            }
        newdata=item +"," + newdata;
        return newdata;
    }

    public static String delete(String item,String data){
        if(data==null || data.isEmpty())
            return null;
        if(! StrUtils.judge(item,data))
            return data;
        String newdata="";
        String [] strings=data.split(",");
        for(String str:strings){
            if(! item.equals(str) && !str.equals(""))
                newdata=newdata+str+",";

        }
        return newdata;
    }

    public static String[] changeToArray(String data){
        if(data==null || data.isEmpty())
            return new String[5];

        return data.split(",");
    }

    public static String[] changeToArray(String data,Integer pageNo, Integer pageSize){
        if(data==null || data.isEmpty())
            return new String[5];

        String [] strings = data.split(",");

        int star = (pageNo - 1) * pageSize;
        int end  = star + pageSize;



        if(end >= strings.length)
            end = strings.length;

        return  Arrays.copyOfRange(strings,star,end);
    }

    public static String ArrayToString(String [] data){
        if(data.length == 0)
            return  "";

      return Arrays.toString(data).replace("[","").replace("]","");
   }
}
